﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace JuCheap.Core.Web.Controllers
{
    public class FileUploadController : Controller
    {
        private readonly IHostingEnvironment _environment;

        public FileUploadController(IHostingEnvironment environment)
        {
            _environment = environment;
        }

        [HttpPost]
        public async Task<IActionResult> OnPostUpload([FromServices]IHostingEnvironment environment)
        {
            string result = string.Empty;
            //  List<string> li = new List<string>();
            var files = Request.Form.Files;
            string webRootPath = environment.WebRootPath;
            string contentRootPath = environment.ContentRootPath;
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var fileName = Guid.NewGuid().ToString() + ".jpg";
                    var path = Path.Combine(environment.WebRootPath, "upload", fileName);
                    using (var stream = new FileStream(path, FileMode.CreateNew))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                    result = fileName;
                }
            }
            return new JsonResult(result);
        }

        [HttpPost("upload/header")]
        public async Task<IActionResult> UploadHeaderImage(IFormFile file)
        {
            var fileName = Guid.NewGuid().ToString("N");

            fileName += Path.GetExtension(file.FileName);

            using (var stream = new FileStream(Path.Combine(_environment.WebRootPath, "hdm", fileName), FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            return Ok(Path.Combine("hdm", fileName));
        }

        [HttpPost("upload/identity")]
        public async Task<IActionResult> UploadIdentityImage(IFormFile file)
        {
            var fileName = Guid.NewGuid().ToString("N");

            fileName += Path.GetExtension(file.FileName);

            using (var stream = new FileStream(Path.Combine(_environment.WebRootPath, "ifm", fileName), FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            return Ok(Path.Combine("ifm", fileName));
        }
    }
}
